package com.penghaisoft.microwms.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseUser;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.dto.UserFactoryDto;
import com.penghaisoft.microwms.common.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
public class BaseController {

	@Value("${auth.expire-time}")
	private Long expireTime;

	@Autowired
	public StringRedisTemplate redisTemplate;

	@Autowired
	public HttpServletRequest request;

	@Autowired
	public HttpServletResponse response;

	@Autowired
	private MessageSource messageSource;
//	/**
//	 * @Description: 开发时允许跨域请求
//	 * @author zxcq0
//	 * @date 2017/3/10 13:40
//	 * @param
//	 * @return
//	 */
//	@ModelAttribute
//	private void allowCrossDomain(HttpServletResponse response){
//		response.addHeader("Access-Control-Allow-Origin","*");
//		response.setHeader("Access-Control-Allow-Headers", "Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin");
//    	response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE,PUT");
//    	response.setHeader("Access-Control-Max-Age", "3600");
//	}


	@InitBinder
	public void bindingPreparation(WebDataBinder binder) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor orderDateEditor = new CustomDateEditor(dateFormat, true);
		binder.registerCustomEditor(Date.class, orderDateEditor);
	}

	/**
	 * 获取cookie中的sesssion
	 * 获取sessionId
	 * @return
	 */
	public String getSessionId(){
		return SessionUtil.getSessionId(request);
	}

	/**
	 * 获取登录人账号
	 * @return
	 */
	public String getLoginName(){
		BaseUser user = getUserInfo();
		String loginName = user.getLoginName();
		return loginName;
	}

	/**
	 * 获取登录人 人名
	 * @return
	 */
	public String getUserName(){
		BaseUser user = getUserInfo();
		String userName = user.getUserName();
		return userName;
	}


	/**
	 * 获取登录人信息
	 * @return
	 */
	public BaseUser getUserInfo(){
		String userInfoJson = (String) SessionUtil.getSessionValue(redisTemplate,SessionUtil.SESSION_USER_INFO+getSessionId());
		BaseUser baseUser = new BaseUser();
		baseUser = JSONObject.parseObject(userInfoJson,BaseUser.class);
		return baseUser;
	}

	/**
	 * 获取登录人关联的工厂
	 * @return
	 */
	public List<UserFactoryDto> getUserFactories(){
		String userFactoriesDtoJson = (String) SessionUtil.getSessionValue(redisTemplate,SessionUtil.SESSION_FACTORY_LIST+getSessionId());
		List<UserFactoryDto> userFactoryDtos = JSONObject.parseArray(userFactoriesDtoJson,UserFactoryDto.class);
		return userFactoryDtos;
	}

	/**
	 * 登录时候放入用户信息
	 * @param baseUser
	 */
	public void sessionLogin(BaseUser baseUser){
		SessionUtil.setSessionValueExpire(redisTemplate, SessionUtil.SESSION_USER_INFO+getSessionId(), com.alibaba.fastjson.JSON.toJSONString(baseUser),expireTime);
	}

	/**
	 * 注销操作
	 * @return
	 */
	public void sessionLogout(){
		String userFactoriesDtoJson = (String) SessionUtil.getSessionValue(redisTemplate,SessionUtil.SESSION_FACTORY_LIST+getSessionId());
		List<UserFactoryDto> userFactoryDtos = JSONObject.parseArray(userFactoriesDtoJson,UserFactoryDto.class);
//		1删除用户的当前工厂
		SessionUtil.removeSessionValue(redisTemplate,SessionUtil.SESSION_CURRENT_FACTORY+getSessionId());
//		2删除用户关联的工厂列表
		SessionUtil.removeSessionValue(redisTemplate,SessionUtil.SESSION_FACTORY_LIST+getSessionId());
//		3 删除用户的信息session
		SessionUtil.removeSessionValue(redisTemplate,SessionUtil.SESSION_USER_INFO+getSessionId());
//		TODO 是否删除用户数据权限？？
	}

	protected TransResult success() {
		TransResult transResult = new TransResult();
		transResult.setCode(Constant.SUCCESS);
		return transResult;
	}

	protected TransResult success(Object data) {
		TransResult transResult = success();
		transResult.setData(data);
		return transResult;
	}

	protected TransResult fail() {
		TransResult transResult = new TransResult();
		transResult.setCode(Constant.FAIL);
		return transResult;
	}

	protected TransResult fail(String msg) {
		TransResult transResult = fail();
		transResult.setMsg(messageSource.getMessage(msg,null,"", LocaleContextHolder.getLocale()));
		return transResult;
	}

	/**
	 * @Description: 根据resp中的code国际化
	 * @author zxcq0
	 * @date 2017/3/14 10:38
	 * @param
	 * @return
	 */
	protected TransResult fromResp(Resp resp) {
		TransResult transResult = new TransResult();
		if (resp.getMsg() != null && !resp.getMsg().equals("")) {
			transResult.setMsg(messageSource.getMessage(resp.getMsg(), null,"", LocaleContextHolder.getLocale()));
		}
		transResult.setCode(resp.getCode());
		return transResult;
	}

	/** 
	 * @Title: getCurrentFactoryCode 
	 * @Description: 获取当前工厂编码
	 * @author zhangxu 
	 * @2017年7月1日:2017年7月1日:上午9:30:54
	 * @param @return    
	 * @return String
	 * @version V0.1    
	 * @throws 
	 */
	protected String getCurrentFactoryCode(){
		String currentFactoryCode = (String)SessionUtil.getSessionValue(redisTemplate,SessionUtil.SESSION_CURRENT_FACTORY+getSessionId());
		return currentFactoryCode;
	}
	
	/** 
	* @Title: getCurrentUserFactoryDto 
	* @Description: 获取当前用户的工厂基本信息
	* @author zhangxu 
	* @2017年8月16日:2017年8月16日:下午12:00:21
	* @param @return    
	* @return UserFactoryDto
	* @version V0.1    
	* @throws 
	*/
	protected UserFactoryDto getCurrentUserFactoryDto(){
		String factoriesJson = (String) SessionUtil.getSessionValue(redisTemplate,SessionUtil.SESSION_FACTORY_LIST+getSessionId());
		List<UserFactoryDto> userFactoryDtos = JSONObject.parseArray(factoriesJson,UserFactoryDto.class);
		for (UserFactoryDto userFactoryDto : userFactoryDtos) {
			if (userFactoryDto.getFactoryCode().equals(getCurrentFactoryCode())) {
				return userFactoryDto;
			}
		}
		return null;
	}

	/**
	 * @Description:  获取一个指定长度的流水号
	 * @Param:  长度
	 * @return:
	 * @Author: zhangx
	 * @Date: 2018/5/8 15:05
	 */
	public String getSerialNo(int length){

		String serialNoStr = "";

		long serialNo = redisTemplate.opsForValue().increment(Constant.SERIALNO,1);
		int serialNoLen = String.valueOf(serialNo).length();

		if (serialNoLen > length){
			serialNo = 1L;
			for (int i = 0; i < length-1; i++) {
				serialNoStr = serialNoStr + "0";
			}
			serialNoStr = serialNoStr + serialNo;
			redisTemplate.opsForValue().set(Constant.SERIALNO,"1");
		}else if (serialNoLen < length){
			for (int i = serialNoLen; i < length; i++) {
				serialNoStr = serialNoStr + "0";
			}
			serialNoStr = serialNoStr +serialNo;
		}else {
			serialNoStr = String.valueOf(serialNo);
		}

		return serialNoStr;

	}


}
